package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.Student;
import service.StudentService;
import utils.Page;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @RequestMapping("/list/{currentPage}")
    public String list(@ModelAttribute("condition") Student condition, @PathVariable("currentPage") Integer currentPage, Model model) {
        // 确保 currentPage 合法


        // 查询数据
        Page page = new Page();
        page.setCurrentPage(currentPage);

        int totalCount = studentService.count(condition);
        page.setTotalCount(totalCount);
        page.setTotalPage();


        // 计算偏移量
        int offset = (currentPage - 1) * page.getPageSize();
        List<Student> students = studentService.findAll2(condition, offset, page.getPageSize());

        // 把对象存到作用域中
        model.addAttribute("page", page);
        model.addAttribute("students", students);

        return "student/list";
    }

    @RequestMapping("/toadd")
    public String toAdd(){
        return "student/add";
    }
    @RequestMapping("/addSave")
    public String addSave(Student student){
         int result = studentService.addStudent(student);
        if (result>0){return "redirect:/student/list/1";}
        else{return "student/add";}
    }
    @RequestMapping("/toupdate/{id}")
    public String toUpdate(@PathVariable("id") Integer id, Model model) {
        Student student = studentService.findStudentById(id);
        model.addAttribute("student", student); // 将学生信息添加到模型中
        return "student/update"; // 返回更新页面
    }

    @RequestMapping("/updateSave")
    public String updateSave(Student student) {
        int result = studentService.updateStudent(student);
        if (result > 0) {
            return "redirect:/student/list/1"; // 更新成功后重定向到第一页
        } else {
            return "student/update"; // 更新失败返回更新页面
        }
    }
    @RequestMapping("/delete/{id}")
    public String deleteById(@PathVariable("id") Integer id) {
        int result = studentService.deleteStudentById(id);
        if (result>0){
            return "redirect:/student/list/1";
        }else {
            return "error";
        } // 删除成功后重定向到第一页
    }

}
